我在JavaScript变量上存储了一些HTML数据,我想从该变量中获取数据
我正在尝试通过getElementById()
方法获得它。另请记住,我在每个div
中都使用了相同的ID。我知道这不是一个好方法,但是有一些限制。所以我需要来自第二个Div
的数据。
var complexArray = "<div id="
post ">First content<\/div><div id="
post ">Second Content<\/div><div id="
post ">Third Content<\/div>";
var data = document.getElementById('post').innerHTML;
alert(data);
答案 0 :(得分:2)
您无法在文档中查询仅存在于字符串变量中的内容。
将该html字符串放入一个临时元素中,并在该元素中查询
将重复的ID改为类,因为ID必须是唯一的
var complexArray = '<div class="post">First content<\/div><div class="post">Second Content<\/div><div class="post">Third Content<\/div>';
// create element to insert the html string into
var tempDiv = document.createElement('div');
tempDiv.innerHTML = complexArray;
// query within that element
var posts = tempDiv.querySelectorAll('.post');
var data = posts[1].innerHTML;
console.log(data);
答案 1 :(得分:0)
您可以使用DOM PARSER。并且id对于每个元素都应该是唯一的,因为您对多个元素使用相同的id,这是错误的。我将id更改为class,<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<div class="container commonDivInvoice">
<div class="row tableInvoice" id="commonDvScroll">
<table class="table table-bordered" id="tableInvoice">
<thead>
<tr>
<th id="itemNameth" class="commanth">Item Name</th>
<th id="itemCodeth" class="commanth">Code</th>
<th id="mrpth" class="commanth">Mrp</th>
<th id="purRateth" class="commanth">Pur.Rate</th>
<th id="unitQtyth" class="commanth">Unit Qty</th>
<th id="discPercentageth" class="commanth">Disc%</th>
<th id="discAmtth" class="commanth">Disc Amt</th>
<th id="gstPercentageth" class="commanth">Gst%</th>
<th id="gstAmtth" class="commanth">Gst Amt</th>
<th id="totalAmtth" class="commanth">Total Amount</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="row tableGrn">
<table class="table table-bordered" id="tfootTable">
<tfoot>
<tr>
<td id="itemNametf" class="commantf" align="center">Total ->
</td>
<td id="itemCodetf" class="commantf"></td>
<td id="mrptf" class="commantd"></td>
<td id="purRatetf" class="commantf"></td>
<td id="unitQtytf" class="commantf"></td>
<td id="discPercentagetf" class="commantf"></td>
<td id="discAmttf" class="commantf"></td>
<td id="gstPercentagetf" class="commantf"></td>
<td id="gstAmttf" class="commantf"></td>
<td id="totalAmttf" class="commantf"></td>
</tr>
</tfoot>
</table>
</div>
id仅适用于post
first element