-1

i am trying to get the value Lotus of the h4 tag from the code below

    <a id="linkSale" class="linkAccess" title="" href="/vp4/Home/Handlers/OperationAccess.ashx?operationid=17285" onclick="javascript:PrepareEventOnLinksAnchor(17285);">

    <h4>Lotus</h4>

    <p class="dateSales">Du <em><strong>mercredi&nbsp;1 mai</strong>&nbsp;9h</em> au <em><strong>dimanche&nbsp;5 mai</strong>&nbsp;6h</em> </p>

    <p class="baseline"></p>

    </a>    

to do that i did as follow :

var h=document.getElementById("17285");

var i=h.getElementsByTagName("h4");

which returned the following line :

<h4>Lotus</h4>

what I want is to get the value Lotus converted to a text.

gic186
  • 786
  • 6
  • 18
Sam
  • 487
  • 4
  • 12
  • 31

5 Answers5

2

Any of these will work - I recommend the last

console.log(
  document.getElementById("linkSale").getElementsByTagName("h4")[0].textContent,
  document.getElementById("linkSale").querySelector("h4").textContent,
  document.querySelector("#linkSale h4").textContent
)
<a id="linkSale" class="linkAccess" title="" href="/vp4/Home/Handlers/OperationAccess.ashx?operationid=17285">
  <h4>Lotus</h4>
  <p class="dateSales">Du <em><strong>mercredi&nbsp;1 mai</strong>&nbsp;9h</em> au <em><strong>dimanche&nbsp;5 mai</strong>&nbsp;6h</em> </p>
  <p class="baseline"></p>
</a>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

you can use jQuery for that :

<h4 id="title">Lotus</h4>

to include script on top:

<script>[[jQuery .js File Path]]</script>

On document ready do like this:

$(document).ready(){ 
     var text=$('#title').html();
});

but I would recommend to use id.

0

You can use "innerHTML" in your example.

 var text = h.getElementsByTagName("h4")[0].innerHTML;

Or "innerText"

var text = h.getElementsByTagName("h4")[0].innerText
hr_117
  • 9,589
  • 1
  • 18
  • 23
-1

You can use jQuery for that :

<h4 id="title">Lotus</h4>

to include script on top:

<script>[[jQuery .js File Path]]</script>

On document ready do like this:

$(document).ready(){ 
     var text=$('#title').html();
});

but I would recommend to use id's or classes

ssedano
  • 8,322
  • 9
  • 60
  • 98
user123_456
  • 5,635
  • 26
  • 84
  • 140
-1

I highly recommend you use jQuery for this type of work. With jQuery, it's pretty easy:

var i = $('h4').text();

However, whenever you can - use the id attribute.

<h4 id="doc_head">Lotus</h4>

Then in JS:

var i = $('#doc_head').text();

If you don't want to use jQuery for some reason - get the text like that (ugly):

var i = h.textContent || h.innerText; // having your DOM object in h

The above should work in both IE and W3C compliant browsers, look here - InnerText alternative in mozilla

Community
  • 1
  • 1