0

Is it possible to add an HTML ID via the browser console using DOM Manipulation?

For example, suppose I am dealing with the following element:

<div class="elementClass">

I can fetch via DOM with something like:

document.getElementsByClassName("elementClass");

However, is it possible to add an attribute via this type of method? If I inspect the element with chrome I can do it manually, but I am wondering if it's possible to inject that ID via JavaScript.

Thanks!

4 Answers 4

1

You can do:

document.getElementsByClassName("elementClass")[0].setAttribute("id", "some ID");
Sign up to request clarification or add additional context in comments.

Comments

1

Yes you can modify attributes of an object (HTMLElement) via javascript

getElementsByclassName returns an array, simply iterate through the list and set the attributes you wish.

var elements = document.getElementsByClassName("elementClass");
for(var I = 0; I < elements.length; I++)
    element[I].id = "element" + I;

Then you could access any of those elements with that class via

 var element = document.getElementById("element" + 0);  //Gets First Element 

Comments

0

Sure.

document.getElementsByClassName('elementClass')[0].id = 'someID';

or

document.getElementsByClassName('elementClass')[0].setAttribute('id', 'someID');

Just know that if you grab elements using getElementsByClassName then it will return an array of elements (assuming any elements with the matching class exist) so modifying the array won't give you the result you want.

Comments

0

setAttribute() method on the DOM element should work just fine.

HTML

<div class="elementClass">
  This is the content of elementClass
</div>

<button onclick="buttonClicked()">Click to add attribute id red to elementClass</button>

Javascript

function buttonClicked(){
 document.getElementsByClassName("elementClass")[0].setAttribute("id", "red");
}

CSS

#red {
  background-color: red;
}

PLAYGROUND

Note that manipulating the class attribute causes the browser to reflow, therefore it is worth mentioning to use setAttribute() wisely to not cause performance issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.