jquery change immediate parent attribute from script
I'm a jquery newbie
If I have a fieldset like this, how can I add new attributes like class="error" and also modify the text of the legend from the script?
I do not know anything about the fieldset or the legend apart from the fact that they exist
<fieldSet>
<legend>My Legend</legend>
<开发者_如何学Go;script type="text/javascript">
//I want to select the legend???
</script>
</fieldset>
To add the class:
$('fieldset').addClass('error');
To modify the legend text:
$('fieldset legend').html('New Legend');
However you need know more information about the fieldset, if you have more then on the page, because the code above will modify all the fieldset tags on it.
From your example above the following would change the text of the 'legend' element and add a class to it -
$("fieldSet legend").text('New Text').addClass('newClass')
You might need to change the $("fieldSet legend")
part of the code depending on what other elements you ultimately display on your page.
EDIT
If you want to refer to a specific fieldset you could do something like this to change the first fieldset on the page -
$("body fieldSet:first-child legend").text('New Text').addClass('newClass')
Otherwise you'd need to add a class or id to the fieldset. So if your fieldset looked like this -
<fieldSet class="chosen">
Your jQuery would need to be -
$("fieldSet.chosen legend").text('New Text').addClass('newClass')
Or if you add an id -
<fieldSet id="chosen">
jQuery -
$("#chosen").text('New Text').addClass('newClass')
There exists workaround for this one.
<fieldSet>
<legend>My Legend 1</legend>
<script type="text/javascript">
var to = 'New Legend 1';
var id = "temp" + Math.floor(Math.random()*100000);
document.write('<span id="'+id+'"></span>');
var temp = $('#'+id); scriptParent = temp.parent(); temp.remove();
scriptParent.find('legend').html(to);
</script>
</fieldset>
<fieldSet>
<legend>My Legend 2</legend>
<script type="text/javascript">
var to = 'New Legend 2';
var id = "temp" + Math.floor(Math.random()*100000);
document.write('<span id="'+id+'"></span>');
var temp = $('#'+id); scriptParent = temp.parent(); temp.remove();
scriptParent.find('legend').html(to);
</script>
</fieldset>
All SCRIPT
elements are evaluated in order as the document is loaded. So, when you use document.write
inside inline SCRIPT
element, the write accours right next to SCRIPT
. Generating unique element after script, and referencing it, could be traced by DOM with ease. You can eaven try creating function for such an action. Just play with it, and I hope, you will understand :)
Try jQAPI for jQuery references if you are new to jQuery.
Have you tried the following expression?
$("legend").html();
精彩评论