te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Replace Node Name - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace Node Name - Stack Overflow

programmeradmin4浏览0评论

Is it possible to replace a nodes name? Like:

HTML:

<strong id="element">Text</strong>

Javascript:

var element = document.getElementById("element");
    element.nodeName = "b";

As I see it's not working, if it's not possible in this way, then how can it be done?

Why I need it:

I'm building a Text Editor, and IE uses strong instead of b in the execCommand() function and I would like to change that, I tried to build the execCommand("bold") from scratch but there is a lots of problem and differences even between IE 8 and 9. So now I decided to change it's node name, it would be really easy, but doesn't works.. :(

Note: I need this to work only in Internet Explorer.

Thanks

Is it possible to replace a nodes name? Like:

HTML:

<strong id="element">Text</strong>

Javascript:

var element = document.getElementById("element");
    element.nodeName = "b";

As I see it's not working, if it's not possible in this way, then how can it be done?

Why I need it:

I'm building a Text Editor, and IE uses strong instead of b in the execCommand() function and I would like to change that, I tried to build the execCommand("bold") from scratch but there is a lots of problem and differences even between IE 8 and 9. So now I decided to change it's node name, it would be really easy, but doesn't works.. :(

Note: I need this to work only in Internet Explorer.

Thanks

Share Improve this question edited Mar 26, 2011 at 17:54 Adam Halasz asked Mar 26, 2011 at 17:42 Adam HalaszAdam Halasz 58.3k67 gold badges153 silver badges216 bronze badges 3
  • 2 What are you trying to achieve? Why is it important for you that your STRONG element has a 'B' name? – Šime Vidas Commented Mar 26, 2011 at 17:47
  • I'm building a Text Editor, and IE uses strong instead of b in the execCommand() function and I would like to change that, I tried to build the execCommand("bold") from scratch but there is a lots of problem and differences even between IE 8 and 9. So now I decided to change it's node name, it would be really easy, but doesn't works.. :( – Adam Halasz Commented Mar 26, 2011 at 17:50
  • I'm working on a replacement for document.execCommand() module for my Rangy library. I have a working bold example now, although it only uses <span style="font-weight: bold"> at the moment. rangy.googlecode./svn/trunk/demos/bold.html – Tim Down Commented Mar 27, 2011 at 1:48
Add a ment  | 

5 Answers 5

Reset to default 5

No, but you can replace the node easily:

var oldNode = document.getElementById('element'),
    newNode = document.createElement('b'),
    node,
    nextNode;

node = oldNode.firstChild;
while (node) {
    nextNode = node.nextSibling;
    newNode.appendChild(node);
    node = nextNode;
}

newNode.className = oldNode.className;
// Do attributes too if you need to
newNode.id = oldNode.id; // (Not invalid, they're not both in the tree at the same time)
oldNode.parentNode.replaceChild(newNode, oldNode);

Live example

Many thanks to Haochi for pointing out replaceChild, I had done this:

oldNode.parentNode.insertBefore(newNode, oldNode);
oldNode.parentNode.removeChild(oldNode);

Live example ...but replaceChild is cleaner.

Docs:

  • DOM2 core
  • DOM2 HTML
  • DOM3 core
Element.prototype.setTagName=function(strTN) {
 var oHTML=this.outerHTML, tempTag=document.createElement(strTN); //document.createElement will fire an error if string has wrong characters.
 var tName={original: this.tagName.toUpperCase(), change: strTN.toUpperCase()}
 if (tName.original == tName.change) return;
 oHTML=oHTML.replace(RegExp("(^\<" + tName.original + ")|(" + tName.original + "\>$)","gi"), function(x){return (x.toUpperCase().replace(tName.original, tName.change));});
 tempTag.innerHTML=oHTML;
 this.parentElement.replaceChild(tempTag.firstChild,this);
}

Use (in case you want to set a span for body's first element):

document.body.firstElementChild.setTagName("SPAN");

EDIT:

I forgot to mention something. It creates a new element so if you have the original one stored in a variable, the variable will be storing the old (unchanged) one. If the Element doesn't have a parent Element it fails.

That's why I made a new one:

Element.prototype.spawn = function(strTN = "spawn") {
 let tName = ({original: this.tagName.toUpperCase(), change: strTN.toUpperCase()}); if (tName.original == tName.change) { return; }
 let fragment = document.createRange().createContextualFragment(this.outerHTML.replace(new RegExp("(^\<\\b" + tName.original + "\\b)|(\\b" + tName.original + "\\b\>$)","gi"), function(x){return(x.toUpperCase().replace(tName.original, tName.change));}));
 return(fragment.firstChild);
}

This one just creates the new Element with all the original descendants but you have to place it to the DOM manually if you want:

var e = document.body.firstElementChild;
e.replaceWith(e.spawn("i"));

You could try getting the outerHTML and replacing the start and end tags.

var element = document.getElementById("element");
element.outerHTML = element.outerHTML.trim()
                                     .replace('<strong ','<button ')
                                     .replace('</strong>'.'</button');

Note well though, the solution above is applicable only for simple use cases. For a better solution go through snippet below.

var element = document.getElementById("element");
changeNodeName(element,'button');

function changeNodeName(el,str){
  var elNodeName = el.nodeName.toLowerCase();
  var newString = el.outerHTML.trim()
                    .replace('<'+ elNodeName,'<'+str);

  // To replace the end tag, we can't simply use replace()
  // because, replace() will replace the first occurrence,
  // which means if our element has a child element with the
  // same node name the end tag of the *child element* will be 
  // replaced, not the parent element. So,

  newString = newString
           .slice(0,newString.lastIndexOf('</'+str+'>'));    
  //now newString = "<button id='element'>Text"

  newString = newString + "</" + str + ">";
  el.outerHTML = newString;
}
<strong id="element">
  <strong>
    Text
  </strong>
</strong>

No, nodeName is read-only. From the spec:

readonly attribute DOMString       nodeName;

See here: http://www.w3/TR/DOM-Level-3-Core/core.html#ID-1950641247

You could store the innerHTML value of the strong element in a temp variable, then create a new "b" element and set its innerHTML to the value stored in the temp variable, and finally use the replaceChild method on the strong element's parent to replace the strong element with the new b element.

发布评论

评论列表(0)

  1. 暂无评论