Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access HTML element without ID?

Tags:

For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?

<div id='header-inner'>     <div class='titlewrapper'>        <h1 class='title'>        Some text I want to change       </h1>     </div>  </div> 

Thanks!

like image 456
JohnIdol Avatar asked Oct 25 '08 16:10

JohnIdol


People also ask

How do I get HTML element without ID or class?

function findFirstDescendant(parent, tagname) { parent = document. getElementById(parent); var descendants = parent. getElementsByTagName(tagname); if ( descendants. length ) return descendants[0]; return null; } var header = findFirstDescendant("header-inner", "h1");

Do HTML elements need ID?

Only put required elements or attributes in HTML. You do not need to put ID attribute if it is not required, and you can always add ID attribute whenever required. Keeping only required elements in html will make it easy to read, clean, low on size and hence improves performance and speed.

Can an ID only be used once HTML?

Yes its in the official specification. You can have more than one element with the same id but it will invalidate your HTML and can cause other problems. You should only use an id once because its means to give you a unique reference to a element in the DOM which is very handy.


2 Answers

function findFirstDescendant(parent, tagname) {    parent = document.getElementById(parent);    var descendants = parent.getElementsByTagName(tagname);    if ( descendants.length )       return descendants[0];    return null; }  var header = findFirstDescendant("header-inner", "h1"); 

Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).

like image 60
Shog9 Avatar answered Sep 25 '22 02:09

Shog9


If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):

var element = $('#header-inner h1'); 

Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.

like image 25
patmortech Avatar answered Sep 22 '22 02:09

patmortech