Change attribute of an element without identification

Asked

Viewed 87 times

3

Is it possible to change some attributes of an element without knowing its identification? Example:

inserir a descrição da imagem aqui

Change the span text to another one of my interest.

2 answers

6

Yes, in many ways, for example in your code:

Using the find() jQuery to find one beaseado element in another:

$( "#panelFormula" ).find( "span" ).css( "background-color", "red" );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="panelFormula">
	<div class="panel-heading">
<span>Fórmula da Critica</span>
</div>


</div>

Finding the element based on its content

$("span:contains(Fórmula da Critica)").css('background-color', 'red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="panelFormula">
	<div class="panel-heading">
<span>Fórmula da Critica</span>
</div>


</div>

In relation to all the elements, finding the span specific that you need

$( "span:nth-child(4)" ).css('background-color', 'red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="panelFormula">
	<div class="panel-heading">
<span></span>  
<span></span>
<span></span>
<span>Fórmula da Critica</span>
</div>


</div>

What’s this all about

This is DOM (Document Object model); it is the element tree that makes up HTML; the above techniques are ways to easily find the elements you need to perform your negotiations, legal?

These articles may be useful too:

2

Based on your code, you can find the span in question and change the text using the selector:

$("#panelFormula > .panel-heading span").text("novo texto");

Example:

$("#panelFormula > .panel-heading span").text("novo texto");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="panelFormula">
   <div class="panel-heading">
      <span>Fórmula da Critica</span>
   </div>
</div>

Wouldn’t use $( "#panelFormula" ).find( "span" ) because it will select all the span within the div#panelFormula, and not just the one you want. That’s because you own a div.panel-body who may have other span, and the .find() will also change the text of these others span who might have.

The selector $("#panelFormula > .panel-heading span") will take the element .panel-heading direct son of #panelFormula and get the span within it, that there is only one.

As element with classes there may be more than one, it is better to be more specific in the selector. If the element .panel-heading is unique within #panelFormula, you can dispense with the sign >, which means "direct child", getting:

$("#panelFormula .panel-heading span").text("novo texto");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.