I have a HTML like the below,
<div id ="div1">
<a class="dropdown-item" href="#" id="success">
<i class="" id="successIcon"></i>
// I need to add the text Success here
</a>
</div>
In Js
Var divId = document.getElementById('div1');
$(divId).find('#success').append("Success"); // Appends everytime "Success" when the PAge is loaded.
Even If I try using,
$(divId).find('#success').text("Success");
$(divId ) .find("#successIcon").attr("class", "fa fa-success text-success");
// The icon "Success" is not appended to the front of the text "Success", if I use text().
I need the Text
as well as the Icon
infront of the text.
Could anyone please help?
Many thanks.
CodePudding user response:
You dont have to use find. You can just use a selector on in $()
.
So you can use:
$('#success').append("Success");
$('#success #successIcon').attr("class", "fa fa-success text-success")
Or since you use id's (which should be unique) you can use:
$('#success').append("Success");
$('#successIcon').attr("class", "fa fa-success text-success")
CodePudding user response:
Try this.i think this is what you are trying to do.
$('#div1 .dropdown-item').append('Success Message here');
$('#div1 .dropdown-item #successIcon').attr('class', 'fa fa-success text-success');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id ="div1">
<a class="dropdown-item" href="#" id="success">
<i class="" id="successIcon"></i>
</a>
</div>
CodePudding user response:
As presented in your question, your code does work (see snippet below)
But there are several things you're not doing tidily:
- use
const
/let
, not var anymore - use jquery selectors instead of
document.getElementById
. That's the power of jQuery fa-success
does not exist in font awesome. You can usefa-ckeck
instead
//Your original code. Just corrected case fo "var" and used "fa-check"
var divId = document.getElementById('div1');
$(divId).find('#success').append("Success");
$(divId).find("#successIcon").attr("class", "fa fa-check text-success");
// How you should have written it
const div2 = $('#div2');
div2.find('#success').append("Success");
div2.find('#successIcon').addClass("fa fa-check text-success");
<!--This is frameworks inclusion -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.1/css/font-awesome.css" />
<!--This is your original html, minus the faulty comment-->
<div id ="div1">
<a class="dropdown-item" href="#" id="success">
<i class="" id="successIcon"></i>
</a>
</div>
<!--This is for second example-->
<div id ="div2">
<a class="dropdown-item" href="#" id="success">
<i class="" id="successIcon"></i>
</a>
</div>