最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get content from id inside id? - Stack Overflow

programmeradmin5浏览0评论

I have HTML like:

<div id='content'>
  <div id='price'>$100</div>
  <div id='another'>something</div>
</div>

I can get content from id="content" like.

vl = document.getElementById("content").value;

In this id, I have another id="price". But I cannot get directly content from id="price".

How can I get content from id="price" through id='content'.Thank you.

I have HTML like:

<div id='content'>
  <div id='price'>$100</div>
  <div id='another'>something</div>
</div>

I can get content from id="content" like.

vl = document.getElementById("content").value;

In this id, I have another id="price". But I cannot get directly content from id="price".

How can I get content from id="price" through id='content'.Thank you.

Share Improve this question asked Mar 19, 2014 at 4:44 Hai TienHai Tien 3,1178 gold badges39 silver badges62 bronze badges 3
  • what's the problem then? – Sunny Sharma Commented Mar 19, 2014 at 4:47
  • 2 possible duplicate of Jquery Get Child DIV Within DIV – Linens Commented Mar 19, 2014 at 4:48
  • Id has to be unique on document, you can use classes instead. – 4EACH Commented Mar 19, 2014 at 4:52
Add a ment  | 

10 Answers 10

Reset to default 3

jQuery:

$("#price").text();

javascript:

document.getElementById("price").innerHTML;

DEMO

You can use as below :

vl = document.getElementById("price").innerHTML;

JSFiddle - Check it out

YOu can also use jquery using .html() or .text() method

Try,

$('#content').html().find('#price').html();

Try this,

var parent = document.getElementById('content');
var childNodes = parent.childNodes;
for(var i = 0, len = childNodes.length;i<len;i++){
    if(childNodes[i].id === "price") {
        alert(childNodes[i].innerHTML);
    }
}

Using jquery,

 $("#content > #price").text();

You can get value of price directly as :

v2 = document.getElementById("price").value;

using Jquery,

v1= $('#content').html();
v2=v1.find('#price');
v3=v1.find('#another')

Try this out:- http://jsfiddle/adiioo7/C3C4x/1/

var price = document.querySelector("#content #price").innerHTML;

console.log(price);

IDs should only be used when there is one of that item on the page. You will have no other chance as to re-assign your IDs, or alternatively using the class attribute.

Try this way to select,

var vl = document.getElementById("content").getElementsByClassName("price")[0];

HTML

 <div id='content'>
   <div class='price'>$100</div>
   <div class='another'>something</div> 
 </div>

You need to access the child element through parent element... that is your question right.. i solve it with jquery DEMO

$(document).ready(function(){
  var tem = $('#content').children('#price').text();
    alert(tem);
});
发布评论

评论列表(0)

  1. 暂无评论