![](/img/trans.png)
[英]javascript create div and append it next to a child element without id
[英]How to append an element to a div which is without id
我想使用javascript在div內添加鏈接,該div沒有id,但是確實有一個類:
<div class="details">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
<a href="#" class="delete">Delete</a>
<div class="compat-meta"></div>
</div>
如何在“詳細信息” div內和“刪除”鏈接上方添加鏈接? 我要添加的鏈接是:
<a href="#edit_link" class="edit">Edit</a>
去jQuery,它簡單干凈。
你可以用特定的類來抓取任何元素
<div class="className" ></div>
像這樣
<script>
$('.className');
</script>
現在您想在具有delete
類的錨點之前添加其他元素,這比您可以做到的要好:
$('.delete').before('<a href="#edit_link" class="edit">Edit</a>');
還有其他方法可以將元素附加到任何其他元素或dom中
1. $('.className').append('<div> i will be appended at the bottom of this element</div>');
2. $('.className').after('<div> i will be appended right after this element</div>');
要使用jquery,您將需要它的api,直接在頁面中使用此鏈接,或者下載最新的jQuery api並使用它。 它越來越簡單。
function hasClass(element, className) {
var s = ' ' + element.className + ' ';
return s.indexOf(' ' + className + ' ') !== -1;
}
/**
* from: http://www.dustindiaz.com/getelementsbyclass
*/
function $class(className, context, tag) {
var classElements = [],
context = context || document,
tag = tag || '*';
var els = context.getElementsByTagName(tag);
for (var i = 0, ele; ele = els[i]; i++) {
if (hasClass(ele, className)) {
classElements.push(ele);
}
}
return classElements;
}
然后使用$class('delete')
定位元素,然后添加新元素
始終最好通過id搜索,這是最有效的。 但是,如果涉及到它,您也可以按類或標記名找到元素。
我建議使用jQuery,並更改現有的標簽:
$('a').attr('href', '#edit_link').text('Edit').removeClass('delete').addClass('edit');
如果無法在找到的元素上添加ID,請在樹中更高位置找到具有ID的元素,然后從那里開始:
$('#someHigherId > div > a')...
您可以使用jQuery:
$('div.details a.delete').before('<a href="#edit_link" class="edit">Edit</a>');
使用純JavaScript:
var div = document.getElementsByClassName('details')[0],
deleteLink = div.getElementsByClassName('delete')[0],
editLink = document.createElement('a');
editLink.textContent = 'Edit';
editLink.className = 'edit';
editLink.href = '#edit_link';
div.insertBefore(editLink, deleteLink);
You can do it using javascript like this
<script type="text/javascript">
function addtext(what){
if (document.createTextNode){
var link = document.createElement('a');
link.setAttribute('href', '#edit_link');
link.setAttribute('id', 'edit');
link.setAttribute('class', 'edit');
document.getElementsByTagName("div")[0].appendChild(link)
document.getElementById("edit").innerHTML = what;
}
}
</script>
<div class="details" id="mydiv" onClick="addtext('Edit')">
<div class="filename">test.xml</div>
<div class="uploaded">25/12/2012</div>
<a href="#" class="delete">Delete</a>
<div class="compat-meta"></div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.