javascriptgetelementsbytagname

How to get ID value from a DIV element using JavaScript


I want to get ID value of this HTML markup.

Example: 123

var id_query = document.querySelector("div.elementor-element-429a9ef");
var id_value = id_query.getElementsByTagName("div")[0].id;
console.log(id_query, id_value)
<div class="elementor-column elementor-col-33 elementor-inner-column elementor-element elementor-element-c44908c" data-id="c44908c" data-element_type="column">
  <div class="elementor-widget-wrap elementor-element-populated">
    <div class="elementor-element elementor-element-429a9ef elementor-widget elementor-widget-heading" data-id="429a9ef" data-element_type="widget" id="1646" data-widget_type="heading.default">
      <div class="elementor-widget-container">
        <div class="elementor-heading-title elementor-size-default">2021-10-10 13:00:00</div>
      </div>
    </div>
  </div>
</div>


Solution

  • You're trying too hard. :) querySelector returns a single element. Simply get its ID value. Of course you can combine the statements or simply use element.id rather than defining a second variable.

    Be sure to use more appropriate variable names. Your first statement didn't return a query. It returned an element.

    const element = document.querySelector("div.elementor-element-429a9ef");
    const id = element.id;
    console.log(id)
    <div class="elementor-column elementor-col-33 elementor-inner-column elementor-element elementor-element-c44908c" data-id="c44908c" data-element_type="column">
      <div class="elementor-widget-wrap elementor-element-populated">
        <div class="elementor-element elementor-element-429a9ef elementor-widget elementor-widget-heading" data-id="429a9ef" data-element_type="widget" id="1646" data-widget_type="heading.default">
          <div class="elementor-widget-container">
            <div class="elementor-heading-title elementor-size-default">2021-10-10 13:00:00</div>
          </div>
        </div>
      </div>
    </div>