setAttribute() not working

html

#1

I'm trying to experiment with this tutorial: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
and when I incorporate this code:

<button name="niceButton" onclick="buttonChange()">Hello World</button>
                <script>
                    function buttonChange() {
                    alert("in buttonChange");
                    var b = document.querySelector("button");

                    b.setAttribute("name", "helloButton");
                    b.setAttribute("disabled", "");
                    }
                </script>

After clicking on the button, when I inspect the source (ctrl+u) in Firefox, the name attribute is still set to "niceButton" instead of "helloButton." What am I missing? Cheers in advance for yourtime. :slight_smile:


#2

If you inspect the source, you'll just get the static markup as served from the backend. To view dynamic changes like this, right-click the button and click "Inspect Element"; this will reveal the element in a tree view of the current state of the DOM.


#3

@m3g4p0p Thank you for your speedy reply! I considered your suggestion and began by right clicking to inspect the element and saw the static markup, however after clicking the button, I checked the element again and the value was the same. :thinking:
The function is working as the "alert" is firing / displaying.


#4

Why using setAttribute() when you can edit the properties?

var b = document.querySelector("button")
b.name = "helloButton"
b.disabled = true

#5

Well if the alert is showing then you might be selecting the wrong button... are there by chance multiple buttons on your page? .querySelector() will only return the first match...

You might also check the console for errors, it's the panel right next to the DOM inspector in dev tools.


#6

@m3g4p0p Yes, there are 2 buttons (and also 2 input type="button"(s)), however when I inspect each of them the name attribute is unchanged. Okay, I'll check the console for errors. So I checked the console and there appears to be an (unrelated) error. SyntaxError: illegal character [Learn More] It shows the error location ( 205:15 [row/column I'm guessing]) and when I went to row 205, col 15 there was no apparent syntax error. :confused:


#7

I copied the code and tested and it works just fine.

As long as you are viewing the inspector (i.e. browser dev tools).

If yours is not working, make sure b is really an element and selecting the right thing.


#8

@zack1 Thank you for getting back with me. I'm not sure I understand what you mean by "make sure b is really an element.".. Isn't b simply a var that is holding the "button" element that is being select by querySelector? How do I verify that b is really an element?


#9

@Dormilich thank you for your recommendation! I tried it, however, it still is not setting the value.
Note: I've also tried editing: document.getElementsByTagName("button")[0].setAttribute("name", "helloButton"); to no avail (using both [0] and [1]). :-/

                <button onclick="myFunction()">get node tag</button>

                <p id="demo"></p>

                <script>
                    function myFunction() {
                        var x = document.getElementById("addButton").parentNode.parentNode.nodeName;
                        document.getElementById("demo").innerHTML = x;
                    }
                </script>

                <button name="niceButton" onclick="buttonChange()">Hello World</button>
                <script>
                    function buttonChange() {
                    alert("in buttonChange");
//I've also tried this:
//document.getElementsByTagName("button")[0].setAttribute("name", "helloButton");
                    var b = document.querySelector("button");
                        b.name = "helloButton";
                        b.disabled = true;
//                    b.setAttribute("name", "helloButton");
//                    b.setAttribute("disabled", "");
                    }
                </script>

#10

You can console.log(b) and see what happens. It should return an element object. If it returns anything else like null or undefined or something then that would be a problem.


#11

@zack1 Okay, so I've been struggling for the last 20 minutes or so to try to determine how to use console.log(b) and I'm not having much success. I found this: https://www.w3schools.com/js/js_output.asp and went through the "Try it yourself": https://www.w3schools.com/js/tryit.asp?filename=tryjs_output_console and can see where the total (in w3schools example) is being displayed in the console, however, I'm not sure where to place console.log in my code. :confused:

@zack1 Oh, and thank you for your patience with me. No doubt you've ascertained my "newbie-ness".


#12

Right after you create/assign it. Here:

var b = document.querySelector("button");

Then the next line can be:

console.log(b);

Since b should now equal something, it will show in the console.

Never mind where it says undefined, that's just because nothing was returned, but you can see there is an html button displayed in the console, so I know this button was the one found and assigned to b.


#13

@zack1 Sweet. So I've placed the console.log as such

<button onclick="myFunction()">get node tag</button>

                <p id="demo"></p>

                <script>
                    function myFunction() {
                        var x = document.getElementById("addButton").parentNode.parentNode.nodeName;
                        document.getElementById("demo").innerHTML = x;
                    }
                </script>

                <button name="niceButton" onclick="buttonChange()">Hello World</button>
                <script>
                    function buttonChange() {

                    alert("in buttonChange");
                        document.getElementsByTagName("button")[0].setAttribute("name", "helloButton");
                        var b = document.querySelector("button");
                        console.log(b);
//                        b.name = "helloButton";
//                        b.disabled = true;
                    b.setAttribute("name", "helloButton");
                    b.setAttribute("disabled", "");
                    }
                </script>

And I'm still not seeing anything in the console - the console tab is blank. I'm accessing the console via f12 > (inspector tab is selected by default) then I select console which is blank.

@zack1 Hmm... still nothing. Just to recap, I'm clicking the "Hello World" button (which fires the buttonChange function, which still fires the alert("in buttonChange"), but doesn't display anything in the console. Unfortunately, I'm going to have to call it for this evening, but I will check to see if you have any additional trouble-shooting suggestions. Hopefully this isn't something simple right under my nose. I've never used console before and I really appreciate you walking me through this.


#14

Very weird then.

Add another log just above that one, as another test :wink:

console.log("hello...world?");

See if that shows up.


#15

Your latest code block is not actually calling buttonChange(). It's calling myFunction(). That would be why the console.log isn't running. I was looking at your original code block.

Assuming you are still calling the buttonChange() function, the console.log should certainly print something out.


#16

@zack1 That's for the "get node tag" button, which I'm not clicking... Thank you sir so much for your help... I've got to go for now. Hope you have a good evening. :slight_smile:


#17

As long as you are actually calling that function, the console log should print something out, even if it's just an error.

This doesn't make sense and is either a really weird configuration or a super simple error we're missing. The querySelector function would return NULL if it can't find an element. Console log would output as much.

I suspect something else is going on. If it were me, I'd use the dev tools debugger to step through the code and see what's happening.


#18

That latest snippet of yours actually works for me too, although it changes the attribute of the "get node tag" button (which it also logs to the console). Maybe try to debug the relevant code in isolation first to rule out other effects...


#19

@zack1 Okay, so per m3g4p0p's suggestion I've tried to isolate the code by creating this:

<?php
/**
 * Created by PhpStorm.
 * User: jcarlisle
 * Date: 11/27/2017
 * Time: 10:10 AM
 */
?>
<p id="demo"></p>

                <button onclick="myFunction()">get node tag</button>

                <button name="niceButton" onclick="buttonChange()">Hello World</button>
                <script>
                    function buttonChange() {

                        alert("in buttonChange");
                        document.getElementsByTagName("button")[0].setAttribute("name", "helloButton");
                        var b = document.querySelector("button");
                        console.log("hello... world?");
                        console.log(b);
//                        b.name = "helloButton";
//                        b.disabled = true;
                        b.setAttribute("name", "helloButton");
                        b.setAttribute("disabled", "");
                    }
                </script>

That seems to have been the trick, now I'm getting "hello... world?" in the console as well the attribute changes to "niceButton". On a sidenote, I'm trying to determine why when I change [0] to [1] BOTH buttons (get node tag and Hello World) are changed. This is in Firefox. In Chrome it handles it properly. Now on to try to figure out why it is not working in my original script. :thinking:


#20

@m3g4p0p Your suggestion was key! (see above post to zack1). Now I'm just having a challenge figuring out why my original code isn't working... Not sure exactly how to troubleshoot it.