Reputation: 341
I'm building a utility base on InboxSDK, that inserts text at the end of your email (but before the signature). InboxSDK gives you the message body as an HTML Element, and I'm trying to use some Jquery to place the text. Where it gets complicated, is the different 'types' of signatures a user could potentially have. I've grouped them into 3.
2 and 3 are the difficult ones. This is the HTML in both cases.
2.
<div id=":nv" class="Am Al editable LW-avf" hidefocus="true" aria-label="Message Body" g_editable="true" role="textbox" contenteditable="true" tabindex="1" style="direction: ltr; min-height: 309px;">
<br clear="all">
<div>
<!--
<div>
Injected Text
</div>
-->
<br>
</div>--
<br>
<div class="gmail_signature" data-smartmail="gmail_signature">
<!-- Signature Content -->
</div>
</div>
3.
<div id=":nv" class="Am Al editable LW-avf" hidefocus="true" aria-label="Message Body" g_editable="true" role="textbox" contenteditable="true" tabindex="1" style="direction: ltr; min-height: 309px;">
<br clear="all">
<div>
<!--
<div>
Injected Text
</div>
-->
<div class="gmail_signature" data-smartmail="gmail_signature">
<!-- Signature Content -->
</div>
</div>
When the '--' exists, I'd like for the new text <div>
I'm injecting to be placed within the first child div. When it doesn't exist I want it as an immediate child of the Message Body, one div before the signature.
What's the most elegant, jquer-ish way to perform this?
Upvotes: 1
Views: 522
Reputation: 341
Ok I think I got it.
var insertDiv = $(`<div>${text}</div>`);
var emailBody = window.gmailComposer.getBodyElement();
if( $('[data-smartmail="gmail_signature"]').length > 0 ) { //if there is indeed a signature block.
if ( $(emailBody).children().has('[data-smartmail="gmail_signature"]').length == 0 ) { //if we have 'double dash' mode enabled.
insertDiv.insertAfter($('[aria-label="Message Body"] > div:not(\'[data-smartmail="gmail_signature"]\'):last'), emailBody); //insert the text in the last div before the "--" div
} else { //'double dash' mode disabled
insertDiv.insertBefore($('[data-smartmail="gmail_signature"]'), emailBody); //insert the text before the signature
}
} else { //no signature
$(emailBody).append(insertDiv); //insert the text at the end of the email
}
Upvotes: 1
Reputation: 22
var foo = $(document.getElementById(":nv")).children("br:first").next();
var divToAdd = $("<div></div>").text("Injected Div");
foo.prepend(divToAdd);
This should work. One thing to note is that $(document.getElementById(":nv")) is faster than $("\\:nv") but you can access the element using either method.
Upvotes: 0
Reputation: 9988
Have you tried to use the jQuery prepend()
in order to append as first child, and the before()/insertBefore()
in order to add before an element?
Here the links to the doc:
http://api.jquery.com/prepend/
Upvotes: 0