[英]Javascript - Div tag auto closing
我正在將網站更改為現代的Web應用程序,這是我的HTML代碼。
<joexn-profile>
<joexn-logo></joexn-logo>
<joexn-text></joexn-text>
</joexn-profile>
這是我用於<joexn-profile>
標記的JavaScript。
var joexnprofile = document.querySelector('joexn-profile');
joexnprofile.insertAdjacentHTML( 'afterBegin', '<center><div class="joexn-profile">');
joexnprofile.insertAdjacentHTML( 'afterEnd', '</div></center>');
問題是<div class="joexn-profile">
標記會自動關閉。
看一下inspect元素視圖:
僅JavaScript
正如昆汀已經解釋的那樣,您不能僅插入節點的一半。
另一方面,為什么要這么做呢?
第一個:避免使用<center>
或<font>
或<b>
類的標簽,...如果要設置樣式。 用CSS來做。
第二:用<div class="joexn-profile">
替換<joexn-profile>
有什么意義?
您應用於.joexn-profile
CSS-Selector的每種樣式也可以應用於joexn-profile
CSS-Selector。
唯一的區別是,您必須為joexn-profile
聲明display:block
,以便瀏覽器知道如何渲染此Node。 block
或inline
或其他。
但是,如果您堅持自己的方式,這里有一個小工具可以處理html標記(甚至部分)和DON-Nodes的這種組合。
免責聲明:代碼未經充分測試,可能仍然包含錯誤。 fragment()
不處理循環引用!
https://jsfiddle.net/mkapLz1k/1/
//just to be clear: this ain't a replacement for jQuery, nor does it interfere with it's purposes.
//it's a set of utilities to enable working with compositions of HTML-Markup and plain DOM-Nodes
var nodeUtils = (function(){
var container = document.createElement("div"),
placeholder = document.createElement("div"),
forEach = Array.prototype.forEach;
function _replacePlaceholder(node){
var parent = node.parentNode;
parent.insertBefore(this[node.id], node);
parent.removeChild(node);
}
function _randomId(){
return ("id"+Math.random()+Math.random()+Math.random()).replace(/0\./g, "-")
}
function _fragment(src){
var markup = [],
nodesById = {},
id = "",
ids = [];
function _addNode(node){
if(!id){
nodesById[id=_randomId()] = fragment();
ids.push("#"+id);
//add placeholder into the html-markup.
//These placeholder get eventually replaced.
markup.push('<div id="'+id+'"></div>');
}
nodesById[id].appendChild( node );
}
function _parse(node){
if(node == null || node === "" || typeof node === "function") return;
if(typeof node === "object"){
if("nodeType" in node){
//processes DOM Nodes, of all shapes and sizes ;)
//including Comment-Nodes, TextNodes and DocumentFragments, ...
_addNode( node );
}else if(this.NodeList && node instanceof NodeList){
//nodeLists change
//so I have to process them differently than regular lists
while(node.length) _addNode( node[0] );
}else{
//processes anything ArrayLike
for(var i = 0, len = ("length" in node && node.length)|0; i<len; ++i)
i in node && _parse( node[i] );
}
}else{
//processes primitives as html-markup
id = "";
markup.push( node );
}
}
_parse( src );
if(ids.length === markup.length){ //=> 0 or 1
//src contained only Nodes, no strings or primitives
return id? nodesById[id]: void 0;
}
//src contained html-markup that needs to be parsed
container.innerHTML = markup.join("");
if(ids.length){
//injecting the DOM-Nodes
forEach.call( container.querySelectorAll( ids.join(",") ), _replacePlaceholder, nodesById );
}
for(var frag = fragment(), fc; fc = container.firstChild; )
frag.appendChild( fc );
return frag;
}
//`fragment()` is shorthand for `document.createDocumentFragment()`
//`fragment(composition)` returns a DocumentFragment, that can be used with `node.appendChild()`.
//takes an arbitrary composition of nested Arrays (or ArrayLike-structures, like jQuery-Objects, NodeLists, ...), containing DOM-Nodes or strings/primitives and builds a DocumentFragment out of that
function fragment(composition){
return composition != null && _fragment(composition) || document.createDocumentFragment();
}
//all the following functions can take anything that `fragment()` can handle as input:
//only `node` has to be a real DOM-Node!
//almost like setting a Nodes innerHTML, but it takes more than just HTML-Markup
function content(node, composition){
for(var frag = fragment(composition), fc; fc=node.firstChild;) node.removeChild(fc);
node.appendChild(frag);
return node;
}
//replace a Node with the provided
function replace(node, composition){
var parent = node.parentNode;
parent.insertBefore(placeholder, node);
parent.insertBefore(fragment(composition), placeholder);
parent.removeChild(placeholder);
//how parent could have changed? maybe you referenced node somewhere in composition.
if(parent === node.parentNode) parent.removeChild(node);
return node;
}
//wraps a Node in the provided markup.
//beforeBegin and afterEnd CAN contain associated markup. Like opening and closing Tag of the same Node.
//e.g.: wrapNode(node, "<div>", "</div>");
function wrapNode(node, beforeBegin, afterEnd){
return replace(node, [beforeBegin, node, afterEnd]);
}
//wraps the content of the node in the provided Markup.
//afterBegin and beforeEnd CAN contain associated markup. Like opening and closing Tag of the same Node.
function wrapContent(node, afterBegin, beforeEnd){
node.appendChild(fragment([afterBegin, node.childNodes, beforeEnd]));
return node;
}
return {
fragment: fragment,
replace: replace,
wrapNode: wrapNode,
wrapContent: wrapContent,
content: content,
}
})();
和您的標記:
var joexnprofile = document.querySelector('joexn-profile');
//telling by your code, it's not entirely clear
//wich of these you actually want to do:
nodeUtils.wrapNode(
joexnprofile,
'<center><div class="joexn-profile">',
'</div></center>'
);
//or
nodeUtils.wrapContent(
joexnprofile,
'<center><div class="joexn-profile">',
'</div></center>'
);
//or maybe
nodeUtils.replace(
//replace this:
joexnprofile,
//with this:
[
'<center><div class="joexn-profile">',
joexnprofile.childNodes,
'</div></center>'
]
);
看一下代碼示例,您對fragment()
能夠處理的內容有第一印象
var frag = nodeUtils.fragment([
//you can build this Array inline, no need to do that beforehand
condition?
window.title:
//simply inject `null` or `undefined` or `""` and this entry will be ignored
null,
//nest Arrays, they get parsed recursively
[
//mix (partial) HTML with other types
'<div class="columns">',
//real Nodes in the middle of some Markup: check
document.getElementById('leftColumn'),
//even more nesting, no problem
[
'<div class="middle">',
//handles anything Arraylike that contains Nodes or Markup
jQuery('.someClass'),
"</div>"
]
'</div>'
],
//NodeLists, no Problem
document.querySelectorAll("#footer > div")
])
現在由您決定如何使用此功能。
盡管insertAdjacentHTML
提供了抽象, insertAdjacentHTML
您仍在處理DOM。 它具有嚴格層次結構中的元素,沒有開始和結束標簽。
HTML將轉換為DOM節點並插入。 您不是在編輯原始源代碼。
請改用createElement
。 使用querySelector
在新元素內獲取所需的元素,然后使用appendChild
將其移動到新元素內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.