Reputation: 42003
I am using a plugin that renders a div style "button", whose html looks like this:
<div id="div-id">
"Button Label"
<input type="file" . . . >
</div>
How do I dynamically change the "Button Label" text with jQuery, while leaving the input intact?
I've tried using .text() but that replaces the input as well.
(Note: I have no control over the HTML that the plugin renders so I'm stuck with this structure).
Thanks!
Upvotes: 0
Views: 164
Reputation: 707198
You can directly access the text node in plain javascript with code like this:
function getFirstTextNode(el) {
var children = el.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType == 3) {
return(children[i]);
}
}
}
var textNode = getFirstTextNode(document.getElementById("div-id"));
textNode.nodeValue = "New Label ";
Upvotes: 1
Reputation: 141869
You could iterate through each node, and look for text nodes with matching content. Once found, only work on that node.
function isTextNode(node) {
return node.nodeType == 3;
}
function hasText(node, text) {
return node.nodeValue.trim() == text;
}
var nodes = $("#root").contents().filter(function() {
return isTextNode(this) && hasText(this, '"Button Label"');
});
nodes.replaceWith("New Label");
Here's an example.
Upvotes: 0
Reputation: 14382
$("#div-id").html(function(i,oldhtml){
return oldhtml.replace("Button Label","New label");
});
Upvotes: 1