2016-12-29 21 views
5

有沒有簡單的方法來改變只使用香草javascript的元素的文本?在下面的代碼中,我認爲使用.textContent而不是.innerHTML會改變文本並將圖像留在後面。使用javascript改變文本只在一個元素

<head> 
    <script> 
     function change_stuff() { 
      var div = document.getElementById('to_change'); 
      div.textContent = "OMG...it's an image!"; 
     } 
    </script> 
</head> 
<body> 
    <div id="to_change"> 
     This is a huge block of text that I want to replace while leaving the image in place 
     <img src="./the_image.jpg"> 
    </div> 
    <button onclick="change_stuff();"> 
     ThE dOER!! 
    </button> 
</body> 

我也試過,但有一點沒有成功與這許多變化:

function change_stuff() { 
    var div = document.getElementById('to_change'); 
    var text = div.textContent; 

    div.textContent = text.replace(text, ""); 
} 

任何幫助,將不勝感激

+0

都能跟得上。那是一廂情願的想法。如果您只想更改該文本或從div中刪除textNode,請將文本放在一個範圍內 – mplungjan

回答

8

通過firstChild屬性獲取第一textNode和更新內容。

function change_stuff() { 
 
    // get the first child node, in your code which is the text node 
 
    var t = document.getElementById('to_change').firstChild; 
 

 
    // update the text contents in the node 
 
    t.nodeValue = ""; 
 

 
    // or t.textContent = ""; 
 

 
    // or remove the node itself 
 
    // t.parentNode.removeChild(t) 
 
}
<div id="to_change"> 
 
    This is a huge block of text that I want to replace while leaving the image in place 
 
    <img src="./the_image.jpg"> 
 
</div> 
 
<button onclick="change_stuff();"> 
 
    ThE dOER!! 
 
</button>

3

W3C DOM (Document Object Model)一切是一個「節點」。節點進來different types(評論節點,元素節點,屬性節點,甚至文本節點)。看起來反直覺的是,像div這樣的元素沒有任何可以包含文本的嵌套元素,它實際上隱含地在其中包含了一個包含原始文本並且該元素是文本節點的子元素。

爲了訪問(這將是從div內的其他元素分開,你可以瀏覽到div和查找(在這種情況下,它的firstChild因爲文字是第一位的,圖像是第二。

而且,當它涉及到用別的東西代替原來的文本...你試圖呼籲divdiv而不是文本字符串.replace()功能,您可以通過隔離div的只是文本導航到其中的文本節點並在其上工作。

function change_stuff() { 
 
    // Get a reference to the div element's text node which is a child node 
 
    // of the div. 
 
    var divText = document.getElementById('to_change').firstChild; 
 
    
 
    // Get the current text within the element: 
 
    var text = divText.textContent; 
 

 
    // You can do whatever you want with the text (in this case replace) 
 
    // but you must assign the result back to the element 
 
    divText.textContent = text.replace(text, ""); 
 
}
<div id="to_change"> 
 
     This is a huge block of text that I want to replace while leaving the image in place 
 
     <img src="./the_image.jpg"> 
 
    </div> 
 
    <button onclick="change_stuff();"> 
 
     ThE dOER!! 
 
    </button>

1

還是務實:

function change_stuff() { 
 
    var div = document.getElementById('to_change'), 
 
    img = div.getElementsByTagName('img')[0]; 
 
    div.innerHTML = "OMG...it's an image!"; 
 
    div.appendChild(img); 
 
}
<div id="to_change"> 
 
    This is a huge block of text that I want to replace while leaving the image in place 
 
    <img src="./the_image.jpg"> 
 
</div> 
 
<button type="button" onclick="change_stuff();"> 
 
    ThE dOER!! 
 
</button>

相關問題