Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getelementbyid and tagname and classname

Tags:

javascript

I want to know how you can get element using pure javascript.

I have my code below:

        <html>
             <body>
                 <div id="abc" class="xy"> 123 </div>
                <p id="abc" class="xyz"> 123 </p>
              <span id="foo" class="foo2"> foo3 </span>
             </body>
           </html>

Here i want to find element with combination:

  1. find element has id abc and tagname p
  2. find element has id abc and classname xy
  3. find element has classname foo2 and tagname span
  4. find element has id abc and classname xy and tagname div

I know we can't use more than one id per page. But in worse situation is it ok to have same ID to different tags? in html?

like image 791
Raj Mehta Avatar asked Aug 17 '12 19:08

Raj Mehta


People also ask

What is the difference between getElementById and getElementsByClassName?

We want to get the unique element and allocate it in a variable this can be done by making use of getElementById. But when we want to get all the products elements and allocate them in a variable then basically we are using getElementByClassName.

What is difference between getElementById and getElementsByName?

The difference is that GetElementByID() will retrieve a single element object based on the unique id specified, whereas GetElementsByTagName() will retrieve an array of all element objects with the specified tag name. Then you can obtain the value using GetElementById from your C++ code.

What is getElementById used for?

Definition and Usage The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.

What is tagname in JavaScript?

Introduction to JavaScript getElementsByTagName() method The getElementsByTagName() is a method of the document object or a specific DOM element. The getElementsByTagName() method accepts a tag name and returns a live HTMLCollection of elements with the matching tag name in the order which they appear in the document.


1 Answers

You can get more "advanced" selection using querySelectorAll. For your three examples:

  1. document.querySelectorAll("p#abc")
  2. document.querySelectorAll(".xy#abc")
  3. document.querySelectorAll("span.foo2")
like image 57
Niet the Dark Absol Avatar answered Sep 24 '22 23:09

Niet the Dark Absol