Javascript 如何在文本上移动dom位置?
假设我有:Javascript 如何在文本上移动dom位置?,javascript,jquery,Javascript,Jquery,假设我有: <span id="root">hello , How are you?<span id="move">Ahmad</span></span> 你好,你好吗?艾哈迈德 我基本上想在单词Hello之后移动ID为move的元素(在5个字符之后),这样我得到Hello Ahmad,你好吗? 在javascript或jquery中是否有我需要的东西?您可以尝试以下方法: let root=document.getElementById(“
<span id="root">hello , How are you?<span id="move">Ahmad</span></span>
你好,你好吗?艾哈迈德
我基本上想在单词Hello
之后移动ID为move
的元素(在5个字符之后),这样我得到Hello Ahmad,你好吗?
在javascript或jquery中是否有我需要的东西?您可以尝试以下方法:
let root=document.getElementById(“root”);
let movable=document.getElementById(“移动”);
root.textContent=
root.firstChild.textContent.slice(0,6)+
movable.textContent+
root.firstChild.textContent.slice(6);
根。移除(可移动);
console.log(root)代码>
你好,你好吗?艾哈迈德取决于你被允许做多少事
纯JS:
var child = document.getElementById("move");
var root = document.getElementById("root");
root.removeChild(child);
root.innerHTML = "Hello " + child.outerHTML + root.innerHTML.split("hello")[1].trim();
JS+次要HTML更新
HTML:
<span id="root">Hello <span id="ending">, How are you?</span><span id="move">Ahmad</span></span>
找到了另一种更简单的方法:
$(document).ready(function(){
var move = $('#move');
var text = $('#root').text();
$('#root').text(text.substring(0, 6));
$('#root').append(move);
$('#root').append(text.substring(6, text.length-5));
});
演示:
$(document).ready(function(){
var move = $('#move');
var text = $('#root').text();
$('#root').text(text.substring(0, 6));
$('#root').append(move);
$('#root').append(text.substring(6, text.length-5));
});